﻿using Dynamics.NAV.Metro.Common;
using Dynamics.NAV.Metro.Data;
using Okra.Core;
using Okra.Navigation;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Dynamics.NAV.Metro.Pages.CustomerDetail
{
    public class CustomerDetailViewModel : BindableBase, IActivatable<NavCustomer, string>
    {
        private NavCustomer _selectedCustomer;
        private IList<NavCustomer> _customers;

        public CustomerDetailViewModel()
        {
            this.GoBackCommand = new DelegateCommand(GoBack);

            NavCustomerDataSource navDataSource = new NavCustomerDataSource();
            this.Customers = navDataSource.GetCustomers();
        }

        [ImportingConstructor]
        public CustomerDetailViewModel(INavCustomerDataSource navCustomerDataSource)
        {
            this.GoBackCommand = new DelegateCommand(GoBack);
            this.Customers = navCustomerDataSource.GetCustomers();
        }

        
        [Import]
        public INavigationManager NavigationManager { get; set; }

        public ICommand GoBackCommand { get; private set; }

        public bool CanGoBack
        {
            get { return NavigationManager.CanGoBack; }
        }

        public void GoBack()
        {
            NavigationManager.GoBack();
        }

        public void Activate(NavCustomer arguments, string state)
        {
            if (arguments == null)
                this.SelectedCustomer = this.Customers.FirstOrDefault();
            else
                this.SelectedCustomer = arguments;
        }

        public string SaveState()
        {
            return null;
        }

        public NavCustomer SelectedCustomer
        {
            get 
            {
                if (this._selectedCustomer == null)
                {
                    this.SelectedCustomer = this.Customers.FirstOrDefault();
                }

                return this._selectedCustomer; 
            }
            set
            {
                if (_selectedCustomer != value)
                {
                    _selectedCustomer = value;
                    OnPropertyChanged("SelectedCustomer");
                }
            }
        }

        public IList<NavCustomer> Customers
        {
            get
            {
                return _customers;
            }
            set
            {
                if (_customers != value)
                {
                    _customers = value;
                    OnPropertyChanged("Customers");
                }
            }
        }
    }
}
